package Reflect.Exercise001;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * ClassName:Reflect
 * Package:Reflect.Exercise001
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/3/8-21:33
 * @Version:v1.0
 */
public class Reflect {
    /*对于任意对象,都可以把对象所有字段名和值,保存到文件中去*/
    public static void main(String[] args) throws IllegalAccessException, IOException {

        Student s = new Student("小A", 23, '女', 167.5, "睡觉");
        Teacher t = new Teacher("波妞", 10000);

        saveObject(s);


    }

    //把对象里面所有的成员变量名和值保存到本地文件中
    public static void saveObject(Object obj) throws IllegalAccessException, IOException {
        Class<?> clazz = obj.getClass();
        //创建IO流
        BufferedWriter bw = new BufferedWriter(new FileWriter("E:\\IDER\\IDEAWorkCode\\IDEADemo\\src\\Reflect\\Exercise001\\a.txt"));
        //获取所有成员变量
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //获取成员变量的名字
            String name = field.getName();
            Object value = field.get(obj);

            bw.write(name + "=" + value);
            bw.newLine();
        }
        bw.close();

    }

}
